package com.wnxy.list;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Vector;
import java.util.concurrent.CopyOnWriteArrayList;

public class App3 {
    /**
     * 解决 ArrayList 线程安全问题 (1) Vector  锁方法
     * 解决 ArrayList 线程安全问题 (2) Collections.synchronizedList 锁代码块
     * 解决 ArrayList 线程安全问题 (3) CopyOnWriteArrayList
     */
    public static void main(String[] args) throws InterruptedException {
        CopyOnWriteArrayList();
    }

    private static void CopyOnWriteArrayList() {
        List list = new CopyOnWriteArrayList();
        for (int i = 0; i < 30; i++) {
            final int temp = i;
            new Thread(() -> {
                list.add(temp);
                System.out.println(list);
            }).start();
        }
    }

    private static void synchronizedList() {
        List list = Collections.synchronizedList(new ArrayList<>());
        for (int i = 0; i < 30; i++) {
            final int temp = i;
            new Thread(() -> {
                list.add(temp);
                System.out.println(list);
            }).start();
        }
    }


    private static void safeVector() {
        List list = new Vector();
        for (int i = 0; i < 30; i++) {
            final int temp = i;
            new Thread(() -> {
                list.add(temp);
                System.out.println(list);
            }).start();
        }
    }
}
